<template lang="html">
  <div class="bluetooth-manager">
    <!-- <div style="text-align: center;">蓝牙管理</div> -->
    <div>
      <!-- 蓝牙搜索 -->
      <div class="bl-switch-cell">
        <van-switch-cell
          title="蓝牙初始化"
          :checked="blueToothChecked"
          @change="switchBluetooth">
        </van-switch-cell>
      </div>
      <!-- 蓝牙搜索 -->
      <!-- 提示 -->
      <div style="font-size: 28rpx; color:#666; padding-left: 30rpx; margin-top: 61rpx;margin-bottom: 11px;overflow: hidden;">
        {{blueToothChecked ? '当前设备' : '请提前打开手机蓝牙'}}<van-loading v-if="discovering" size="28rpx" />
        <!-- 重新检索 -->
        <van-button type="primary" custom-class="refind-btn" v-if="!discovering && available && blueToothChecked" @click="startSearchBTDev">开始搜索</van-button>
        <!-- 停止搜索 -->
        <van-button type="primary" custom-class="refind-btn" v-if="discovering && available && blueToothChecked" @click="stopSearchBTDev">停止搜索</van-button>
      </div>
      <!-- 检索到的蓝牙 -->
      <van-cell-group custom-class="bt-list">
        <van-cell v-for="item in devData" :key="item.deviceId" class="bt-item">
          <span slot="title" class="dev-single-name">
            <span class="single">
              <span :class="{cgreen: item.RSSI >= 1}"></span>
              <span :class="{cgreen: item.RSSI >= 2}"></span>
              <span :class="{cgreen: item.RSSI >= 3}"></span>
              <span :class="{cgreen: item.RSSI >= 4}"></span>
              <span :class="{cgreen: item.RSSI >= 5}"></span>
            </span>
            <span class="dev-name">{{item.name}}</span>
          </span>
          <!-- <button type="default" size="mini" class="link-btn">连接</button> -->
          <van-button plain type="primary" custom-class="link-btn" @click="linkBLE(item.deviceId)" v-if="BTPrintStatus !== item.deviceId">连接</van-button>
          <van-button plain type="primary" custom-class="link-btn activelink" @click="closeBLE(item.deviceId)" v-if="BTPrintStatus === item.deviceId">断开</van-button>
        </van-cell>
      </van-cell-group>
    </div>
    <van-toast id="van-toast" />
  </div>
</template>

<script>
/* eslint-disable */
import {openBTAdapter, closeBTAdapter, onListernerBTState, getBTAdapterState, startDisBTDev, onListenerBTDevFound, stopDisBisBTDev, connectBLEDev, closeConnectBLEDev} from '@/utils/bluetooth.js'
import Toast from '../../../static/vant/toast/toast.js'
import store from '@/store/globalStore.js'
import {alert, navigateBack, showLoading, hideLoading} from '@/utils/wxapi.js'
import {versionCompare} from '@/utils/'
/* eslint-disable */
export default {
  name: 'BlueTooth',
  data () {
    return {
      blueToothChecked: false,
      available: false, // 蓝牙适配器是否可用
      discovering: false, // 是否处于搜索状态
      devData: [
        // {
        //   name: '测试打印机',
        //   localName: '测试打印机',
        //   deviceId: '12sdfdsf32132132',
        //   RSSI: '3'
        // },
        // {
        //   name: 'WeLoop Now2 ED53E4',
        //   localName: '测试打印机',
        //   deviceId: '1232132132',
        //   RSSI: '4'
        // }
      ]
    }
  },
  onUnload () {
    console.log('蓝牙页面 onUnload')
    // 如果处于搜索状态，停止搜索
    stopDisBisBTDev()
  },
  computed: {
    BTPrintStatus () {
      return store.state.BTEDevId
    }
  },
  mounted () {
    console.log('蓝牙页面 mounted')
    // console.log(this.$mp)
    // let json = {
    //   name: '123123'
    // }
    // this.$set('devData', json)
    // this.$root.$mp.query
    // console.log(this)
    console.log(store.state)
    const sysInfo = store.state.sysInfo
    // 判断微信版本，系统版本
    if (sysInfo.platform == 'android' && versionCompare('6.5.7', sysInfo.version)) {
      alert('当前微信版本过低，请升级')
      navigateBack(1)
    } else if (sysInfo.platform == 'android' && versionCompare('4.3.0', sysInfo.system)) {
      alert('当前安卓版本过低，请升级')
      navigateBack(1)
    } else if (sysInfo.platform == 'ios' && versionCompare('6.5.6', sysInfo.system)) {
      alert('当前微信版本过低，请升级')
      navigateBack(1)
    }

    // 监听蓝牙状态
    onListernerBTState(res => {
      this.available = res.available // 蓝牙适配器是否可用
      this.discovering = res.discovering // 是否处于搜索状态
      if (!this.available) {
        this.blueToothChecked = false // 蓝牙初始化按钮关闭
        // 关闭蓝牙模块
        closeBTAdapter().then(() => {
          this.devData = [] // 清空列表
          store.commit('commitChangeBTStatus', '')
        })
        Toast('请打开手机蓝牙')
        // global
      }
    })
    // if (this.available && !this.discovering) {
    //   // 开始检索设备
    //   this.startSearchBTDev()
    // }
  },
  methods: {
    // 打开蓝牙
    switchBluetooth (e) {
      console.log(e.mp.detail)
      this.blueToothChecked = !this.blueToothChecked
      if (e.mp.detail) {
        // 初始化蓝牙
        openBTAdapter().then(res => {
          // console.log(code)
          // 成功
          console.log('蓝牙初始化成功')
          // Toast('蓝牙初始化成功')
          // 开始搜索设备
          this.startSearchBTDev()
        }).catch(err => {
          // 出错
          // console.log(err)
          Toast.fail(err)
          this.blueToothChecked = false // 关闭switch
        })
      } else {
        this.available = false
        this.discovering = false
        // 断开蓝牙模块
        closeBTAdapter().then(() => {
          // 成功
          // Toast('蓝牙断开成功')
          store.commit('commitChangeBTStatus', '')
          this.devData = []
        }).catch(err => {
          // 出错
          Toast(err)
          // this.blueTooth
        })
      }
    },
    // 开始搜索蓝牙列表
    startSearchBTDev () {
      // 获取本机蓝牙适配器状态
      getBTAdapterState().then(res => {
        let available = res.available // 蓝牙适配器是否可用
        let discovering = res.discovering // 是否处于搜索状态
        console.log(available, discovering)
        if (available && !discovering) {
          // 扫描附近设备
          startDisBTDev().then(res => {
            console.log('扫描成功', res)
            // 开始监听新设备
            onListenerBTDevFound(this)
          }).catch(err => {
            Toast(err)
          })
        }
      }).catch(err => {
        Toast(err)
      })
    },
    // 连接BLE
    linkBLE (deviceId) {
      console.log(deviceId)
      connectBLEDev(deviceId, () => {
        // 成功的回调
        // listenerBLEConnectionState(deviceId)
      })
    },
    closeBLE (deviceId) {
      closeConnectBLEDev(deviceId)
    },
    stopSearchBTDev () {
      stopDisBisBTDev()
    }
  }
}
</script>

<style lang="scss">
.bluetooth-manager {
  .section {
    padding: 10px;
    border-top: 1px solid #efefef;
    border-bottom: 1px solid #efefef;
  }
  .van-switch--on {
    background-color: #4EB331;
  }
  .bl-switch-cell {
    margin-top: 61rpx;
    border-top: 1rpx solid #DFDFDF;
    border-bottom: 1rpx solid #DFDFDF;
    .van-cell__title {
      color: #333333;
      font-size: 34rpx;
    }
  }
  // 重新搜索按钮
  .refind-btn {
    font-size: 26rpx;
    padding: 0;
    height: 54rpx;
    line-height: 54rpx;
    float: right;
    margin-right: 15px;
    width: 130rpx;
  }
  .bt-list {
    .cgreen {
      background: #4EB331 !important;
    }
    .van-cell {
      font-size: 32rpx;
      align-items: center;
    }
    .bt-item {}
    .link-btn {
      font-size: 26rpx;
      background: white;
      border: 1rpx solid #4EB331;
      color: #4EB331;
      width: 120rpx;
      height: 54rpx;
      border-radius: 6rpx;
      text-align: center;
      line-height: 54rpx;
      padding: 0;
      margin: 0;
    }
    // 断开按钮
    .activelink {
      background: #4EB331;
      color: white;
    }
    .dev-single-name {
      width: 500rpx;
      // display: inline-block;
      white-space:nowrap;
      overflow:hidden;
    }
    .dev-name {
      // width: 350rpx;
      display: inline-block;
    }
    .single {
      // position: relative;
      display: inline-flex;
      justify-content: space-between;
      align-items: baseline;
      // width: 24rpx;
      heigth: 22rpx;
      margin-right: 16rpx;
      & > span {
        width: 4rpx;
        height: 22rpx;
        background: rgba(0,0,0,0.1);
        margin: 0 1rpx;
        &:nth-of-type(1) {
          height: 8rpx;
        }
        &:nth-of-type(2) {
          height: 12rpx;
        }
        &:nth-of-type(3) {
          height: 15rpx;
        }
        &:nth-of-type(4) {
          height: 19rpx;

        }
        &:nth-of-type(5) {
          height: 22rpx;
        }
      }
    }
  }
}
</style>
